/*
 * Copyright (C) 2011, 2012 Moravská zemská knihovna v Brně / Moravian Library in Brno
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mzk.oai.provider.response.listRequests;

import cz.mzk.oai.metadataRepository.repository.records.Record;
import cz.mzk.oai.provider.Configuration;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import org.joda.time.DateTime;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class RequestSequence {

    private static final Logger logger = Logger.getLogger(RequestSequence.class.getName());
    private final CompleteList request;
    private final int cursor;
    private final int maxRecordsReturned;
    private final DateTime validUntil;

    public RequestSequence(CompleteList request, int cursor, int maxRecordsReturned) throws IOException {
        this.request = request;
        this.cursor = cursor;
        this.maxRecordsReturned = maxRecordsReturned;
        DateTime now = new DateTime();
        this.validUntil = now.plusMinutes(Configuration.instanceOf().getListRequestsMinutesValid());
    }

    RequestSequence nextPart() throws IOException {
        int nextCursor = nextCursor();
        if (nextCursor < request.totalSize()) {
            return new RequestSequence(request, nextCursor, maxRecordsReturned);
        } else {
            logger.fine("last request sequence");
            return null;
        }
    }

    public CompleteList getRequest() {
        return request;
    }

    public List<Record> getRecords() {
        return request.getRecords(cursor, nextCursor(), maxRecordsReturned);
    }

    public int cursor() {
        return cursor;
    }

    private int nextCursor() {
        return cursor + maxRecordsReturned;
    }

    public DateTime getValidUntil() {
        return validUntil;
    }
}
